package com.example.pan.ui.download

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.pan.R
import com.example.pan.databinding.FragmentDownloadBinding
import com.example.pan.model.DownloadTaskInfo
import com.example.pan.ui.getAvailSpace
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi

@AndroidEntryPoint
class DownloadFragment : Fragment(R.layout.fragment_download) {

    private val binding: FragmentDownloadBinding by viewbind()
    private val mViewModel: DownloadViewModel by viewModels()
    private val adapter = DownloadAdapter()

    @ExperimentalCoroutinesApi
    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mViewModel.tellAllTask().observe(viewLifecycleOwner) { data ->
            adapter.submitList(data)
        }

        val recyclerView = binding.downloadList
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = adapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        // recyclerView.addItemDecoration(
        //     DividerItemDecoration(
        //         context,
        //         DividerItemDecoration.VERTICAL
        //     )
        // )
        adapter.setOnItemClickListener(object : DownloadAdapter.OnItemClickListener {
            override fun onItemClick(item: DownloadTaskInfo) {

            }

            override fun onPause(item: DownloadTaskInfo) {
                mViewModel.pause(item.gid).observe(this@DownloadFragment.viewLifecycleOwner) {
                    Toast.makeText(this@DownloadFragment.context, it, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onUnPause(item: DownloadTaskInfo) {
                mViewModel.unPause(item.gid).observe(this@DownloadFragment.viewLifecycleOwner) {
                    Toast.makeText(this@DownloadFragment.context, it, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onRemove(item: DownloadTaskInfo) {
                mViewModel.remove(item.gid).observe(this@DownloadFragment.viewLifecycleOwner) {
                    Toast.makeText(this@DownloadFragment.context, it, Toast.LENGTH_SHORT).show()
                }
            }

        })
        binding.devInfo.text = "可用：${getAvailSpace()}"
    }

    @ExperimentalCoroutinesApi
    override fun onResume() {
        super.onResume()

    }

}